<template>
  <view>
    <nav-bar :pageTitle="lang.page_name"/>
    <view style="margin:0 30rpx 0 30rpx;" :class="locale">
      <view class="upload-box">

        <!-- 照片选自框大 box-->
        <view class="flex-column gap-30">
          <view class="column-center gap-20">
            <view class="registration-card-box">
              <view v-if="businessLicenseFront === ''" hover-class="hover" @click="showUploadImage">
                <view class="column-center icon-card-box">
                  <view class="flex-column icon-card">
                    <u-icon size="44px" color="#1073FF" name="camera"/>
                  </view>
                </view>
                <image class="registration" src="/static/print_id/business_license.svg"/>
              </view>

              <template v-else>
                <view class="close-icon-box" @click="closeRegistration">
                  <u-icon size="26px" color="#0009" name="close-circle-fill"/>
                </view>
                <view @click="onEditImage">
                  <image class="registration" :src="businessLicenseFront"/>
                </view>
              </template>
            </view>
            <view class="text-32">{{ lang.business_license_front }}</view>
          </view>
        </view>
      </view>

      <!-- 打印-->
      <view style="margin-top: 30rpx">
        <u-button
            :disabled="!businessLicenseFront" shape="circle" @click="registrationDrawAndShareImage"
            size="large" color="#1073FF" :customStyle="{fontSize: '32rpx' }">
          {{ otherLang.print }}
        </u-button>
      </view>

      <!-- a4 打印-->
      <view class="canvas">
        <canvas style="width: 1588px; height: 2246px; " canvas-id="businessLicenseFrontCanvas"
                id="businessLicenseFrontCanvas"/>
      </view>

      <!--    上传中弹窗-->
      <my_upload_card :upload-name="lang.business_license_upload" :show="showUpload"
                      :upload-progress="uploadProgress"/>

      <!-- 选择弹窗-->
      <upload-select-popup
          :show-popup="showUploadPopup" @choose-message="chooseMessage" @choose-image="chooseImage"
          @close-popup="showUploadPopup = false"/>
    </view>
  </view>
</template>

<script>
import tips from "@/utils/tips";
import navBar from "@/components/nav-bar/nav-bar.vue";
import my_upload_card from "@/components/my_upload_card/index.vue";
import uploadSelectPopup from "@/components/upload-select-popup/upload-select-popup.vue";
import {editImageChange} from "@/utils/utils";
import {uploadImageServer} from "@/services/office";

export default {
  name: "print_business_license",
  components: {navBar, uploadSelectPopup, my_upload_card},
  data() {
    return {
      businessLicenseFront: '',
      showUploadPopup: false,
      showUpload: false,
      uploadProgress: 0,
    };
  },
  computed: {
    lang() {
      return this.$t('print_business_license')
    }
  },
  methods: {
    showUploadImage() {
      this.showUploadPopup = true;
    },
    // 微信选取图片
    chooseMessage() {
      const that = this;
      uni.chooseMessageFile({
        count: 1,
        type: 'image',
        success(res) {
          editImageChange(res.tempFiles[0].path).then((tempFilePath) => {
            that.businessLicenseFront = tempFilePath
          }).finally((err) => {
            console.log(err)
          })
        }
      });
    },

    // 本地图片上传或拍照
    chooseImage(index) {
      const that = this;
      const sourceTypes = ['camera', 'album'];
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: [sourceTypes[index]],
        sizeType: ['original', 'compressed'],
        success: function (res) {
          editImageChange(res.tempFiles[0].tempFilePath).then((tempFilePath) => {
            that.businessLicenseFront = tempFilePath
          }).finally((err) => {
            console.log(err)
          })
        }
      });
    },

    // 删除照片
    closeRegistration() {
      this.businessLicenseFront = '';
    },

    // 编译图片
    onEditImage() {
      editImageChange(this.businessLicenseFront).then((tempFilePath) => {
        console.log(tempFilePath)
        this.businessLicenseFront = tempFilePath
      })
    },

    // 合成图片
    registrationDrawAndShareImage() {
      // 绘制背景海报到canvas
      // 长143毫米，宽105毫米 户口本宽高 * 8
      const posterWidth = 0;      // 营业宽度
      const posterHeight = 0;     // 营业高度
      const a4Width = 1588;         // A4纸宽度
      const a4Height = 2246;        // A4纸高度

      const that = this;

      // 检查是否已上传照片
      if (!that.businessLicenseFront) {
        tips.toast("请先上传图片")
        return;
      }

      uni.showLoading({title: '加载中....', mask: true})

      // 微信小程序特有代码
      const context = uni.createCanvasContext('businessLicenseFrontCanvas', this);

      context.fillStyle = "#FFFFFF";
      context.fillRect(0, 0, a4Width, a4Height);

      context.drawImage(that.businessLicenseFront, posterWidth, posterHeight, a4Width, a4Height);
      context.draw();

      setTimeout(() => {
        uni.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: a4Width,
          height: a4Height,
          destWidth: a4Width,
          destHeight: a4Height,
          canvasId: 'businessLicenseFrontCanvas',
          success: (res) => {
            console.log(":businessLicenseFrontCanvas -=-=", res);
            // 上传图片到服务器
            uni.uploadFile({
              url: uploadImageServer,
              name: 'file',
              filePath: res.tempFilePath,
              success: (res) => {
                console.log("success: (res) => -=-=-", res)
                const {code, data: {url}} = JSON.parse(res.data);
                console.log("Upload success:", JSON.parse(res.data).data);
                if (code === 200) {
                  uni.navigateTo({url: `/pages/photo_pay/photo_pay?type=1&image=` + encodeURIComponent(JSON.stringify(url))})
                }
              },
              fail: (err) => {
                console.error('Upload failed:', err);
              }, complete: () => {
                uni.hideLoading()
              }
            });
          }
        });
      }, 1500)
    },
  }
}
</script>

<style lang="scss">
.registration-card-box {
  width: 560rpx;
  height: 800rpx;
  position: relative;
  border-radius: 16rpx;
  padding: 4rpx;
  border: 2rpx dashed #1073FF;
}

.registration {
  width: 552rpx;
  height: 800rpx;
  border-radius: 16rpx;
}
</style>
